//
//  ABClockView.m
//  ABClockView
//
//  Created by Boris Emorine on 2/23/14.
//  Copyright (c) 2014 Boris Emorine. All rights reserved.
//

#import "ABClockView.h"
@interface ABClockView () {
    
    BOOL shouldUpdateSubviews;
    
    BOOL timerAlreadyInAction;
    
    BOOL skipOneCycle;
    
    BOOL _realTimeIsActivated;
    
}

/**
 *  分针旧值
 */
@property (nonatomic, assign) NSInteger oldMinutes;
/**
 *  时针
 */
@property (nonatomic, strong) ABHand *hourHand;
/**
 *  分针
 */
@property (nonatomic, strong) ABHand *minuteHand;
/**
 *  秒针
 */

@property(nonatomic,retain)    PanView *drawRound;//蒙版
@property (nonatomic, strong) ABHand *secondHand;
@property(nonatomic,assign)CGFloat  clockWidth;//表半径
@end

@implementation ABClockView

#pragma mark - 懒加载
//蒙版
-(PanView *)drawRound
{
    if (!_drawRound) {
        _drawRound = [[PanView alloc]initWithFrame:self.bounds];
        [self addSubview:_drawRound];
    }
    return _drawRound;
}

-(void)setMaskViewProgress:(NSString *)maskViewProgress
{
    self.drawRound.progress = maskViewProgress;
    if ([self.drawRound.progress floatValue] > 1) {
        self.drawRound = nil;
    }
}
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.clockWidth = frame.size.width/2.0;
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    // 默认值配置
    _hours = 10;
    _minutes = 10;
    _seconds = 0;
    
    _realTime = NO;
    _currentTime = NO;
    
    _faceBackgroundColor = [UIColor clearColor];
    _faceBackgroundAlpha = 0;
    //表盘外边框
    _borderColor = [UIColor redColor];
    _borderAlpha = 1.0;
    _borderWidth = 0;
    //时针
    _hourHandColor = [UIColor redColor];
    _hourHandAlpha = 1.0;
    _hourHandWidth = .8;
    _hourHandLength = 3 * _clockWidth / 25.0;
    _hourHandOffsideLength = 2;
    //分针
    _minuteHandColor = [UIColor whiteColor];
    _minuteHandAlpha = 1.0;
    _minuteHandWidth = .8;
    _minuteHandLength = 5 * _clockWidth / 25.0;
    _minuteHandOffsideLength = 2;
    //秒针
    _secondHandColor = [UIColor whiteColor];
    _secondHandAlpha = 1.0;
    _secondHandWidth = .6;
    _secondHandLength = 8 * _clockWidth / 25.0;
    _secondHandOffsideLength = 2;
    
    //刻度
    self.graduationColor = [UIColor blackColor];
    
    self.graduationAlpha = 1.0;
    
    self.graduationWidth = 1.0;
    
    self.graduationLength = 3.0;
    
    self.graduationOffset = 0;
    
    
    self.backgroundColor = [UIColor yellowColor];
    shouldUpdateSubviews = YES;
    timerAlreadyInAction = NO;
    skipOneCycle = NO;
    _realTimeIsActivated = NO;
}

- (void)layoutSubviews
{
    if (shouldUpdateSubviews == YES) {
        
        if (self.currentTime == YES) {
            [self setClockToCurrentTimeAnimated:YES];
        }
        
        [self timeFormatVerification];
        self.hourHand = [[ABHand alloc] initWithFrame:self.bounds];
        self.hourHand.degree = [self degreesFromHour:self.hours andMinutes:self.minutes];
        self.hourHand.color = self.hourHandColor;
        self.hourHand.alpha = self.hourHandAlpha;
        self.hourHand.width = self.hourHandWidth;
        self.hourHand.length = self.hourHandLength;
        self.hourHand.offsetLength = self.hourHandOffsideLength;
        [self addSubview:self.hourHand];
        
        self.minuteHand = [[ABHand alloc] initWithFrame:self.bounds];
        self.minuteHand.degree = [self degreesFromMinutes:self.minutes];
        self.minuteHand.color = self.minuteHandColor;
        self.minuteHand.alpha = self.minuteHandAlpha;
        self.minuteHand.width = self.minuteHandWidth;
        self.minuteHand.length = self.minuteHandLength;
        self.minuteHand.offsetLength = self.minuteHandOffsideLength;
        [self addSubview:self.minuteHand];
        
        self.secondHand = [[ABHand alloc] initWithFrame:self.bounds];
        self.secondHand.degree = [self degreesFromMinutes:self.seconds];
        self.secondHand.color = self.secondHandColor;
        self.secondHand.alpha = self.secondHandAlpha;
        self.secondHand.width = self.secondHandWidth;
        self.secondHand.length = self.secondHandLength;
        self.secondHand.offsetLength = self.secondHandOffsideLength;
        [self addSubview:self.secondHand];
        
        if (self.realTime == YES && timerAlreadyInAction == NO) {
            _realTimeIsActivated = YES;
            timerAlreadyInAction = YES;
            [NSTimer scheduledTimerWithTimeInterval:1.0
                                             target:self
                                           selector:@selector(updateEverySecond)
                                           userInfo:nil
                                            repeats:YES];
        }
        shouldUpdateSubviews = NO;
        

    }
}
#pragma mark - 更新时间
- (void)updateEverySecond {
    if (_realTimeIsActivated == YES) {
        self.seconds = self.seconds + 1;
        if (skipOneCycle == YES) {
            skipOneCycle = NO;
        } else {
            [self timeFormatVerification];
            [self.secondHand setDegree:[self degreesFromMinutes:self.seconds] animated:YES];
        }
    }
}

- (void)setClockToCurrentTimeAnimated:(BOOL)animated
{
    NSDate *currentTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh"];
    NSString *currentHour = [dateFormatter stringFromDate: currentTime];
    [dateFormatter setDateFormat:@"mm"];
    NSString *currentMinute = [dateFormatter stringFromDate: currentTime];
    [dateFormatter setDateFormat:@"ss"];
    NSString *currentSecond = [dateFormatter stringFromDate: currentTime];
    self.hours = [currentHour integerValue];
    self.minutes = [currentMinute integerValue];
    self.seconds = [currentSecond integerValue];
    skipOneCycle = animated;
    [self.minuteHand setDegree:[self degreesFromMinutes:self.minutes] animated:animated];
    [self.hourHand   setDegree:[self degreesFromHour:self.hours andMinutes:self.minutes] animated:YES];
    [self.secondHand setDegree:[self degreesFromMinutes:self.seconds] animated:YES];
}

#pragma mark - 转换计算
- (void)timeFormatVerification {
    if (self.hours > 12 ) // If the time has been set to military time, converts it to 12-hour clock.
        self.hours = self.hours - 12;
    
    if (self.seconds >= 60) {
        self.seconds = 0;
        self.minutes = self.minutes + 1;
        [self.minuteHand setDegree:[self degreesFromMinutes:self.minutes] animated:YES];
        [self.hourHand   setDegree:[self degreesFromHour:self.hours andMinutes:self.minutes] animated:YES];
    }
    else if (self.seconds < 0) {
        self.seconds = 59;
        self.minutes = self.minutes - 1;
        [self.minuteHand setDegree:[self degreesFromMinutes:self.minutes] animated:YES];
        [self.hourHand   setDegree:[self degreesFromHour:self.hours andMinutes:self.minutes] animated:YES];
    }
    
    if (self.minutes >= 60) {
        self.minutes = 0;
        self.hours = self.hours + 1;
    }
    else if (self.minutes < 0) {
        self.minutes = 59;
        self.hours = self.hours - 1;
    }
    if (self.hours >= 13) {
        self.hours = 1;
    } else if (self.hours <= 0) {
        self.hours = 12;
    }
}

- (float)degreesFromHour:(NSInteger)hour andMinutes:(NSInteger)minutes {
    float degrees = (hour*30) + (minutes/10)*6;
    return degrees;
}

- (float)degreesFromMinutes:(NSInteger)minutes {
    float degrees = minutes*6;
    return degrees;
}
#pragma mark - 绘图
- (void)drawRect:(CGRect)rect {
    // 表盘
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, rect);
    CGContextSetFillColorWithColor(ctx, self.faceBackgroundColor.CGColor);
    CGContextSetAlpha(ctx, self.faceBackgroundAlpha);
    CGContextDrawImage(ctx, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), [[UIImage imageNamed:@"icon29"] CGImage]);
    CGContextFillPath(ctx);
    // 边框
    CGContextAddEllipseInRect(ctx, CGRectMake(rect.origin.x + self.borderWidth/2, rect.origin.y + self.borderWidth/2, rect.size.width - self.borderWidth, rect.size.height - self.borderWidth));
    CGContextSetStrokeColorWithColor(ctx, self.borderColor.CGColor);
    CGContextSetAlpha(ctx, self.borderAlpha);
    CGContextSetLineWidth(ctx,self.borderWidth);
    CGContextStrokePath(ctx);
    // 刻度
    for (int i = 0; i<60; i += 1)
    {

        if (i % 5 != 0) continue;
        CGPoint P1 = CGPointMake((self.frame.size.width/2 + ((self.frame.size.width - self.borderWidth*2 - self.graduationOffset) / 2) * cos((6*i)*(M_PI/180)  - (M_PI/2))), (self.frame.size.width/2 + ((self.frame.size.width - self.borderWidth*2 - self.graduationOffset) / 2) * sin((6*i)*(M_PI/180)  - (M_PI/2))));
        CGPoint P2 = CGPointMake((self.frame.size.width/2 + ((self.frame.size.width - self.borderWidth*2 - self.graduationOffset - self.graduationLength) / 2) * cos((6*i)*(M_PI/180)  - (M_PI/2))), (self.frame.size.width/2 + ((self.frame.size.width - self.borderWidth*2 - self.graduationOffset - self.graduationLength) / 2) * sin((6*i)*(M_PI/180)  - (M_PI/2))));
        
        CAShapeLayer  *shapeLayer = [CAShapeLayer layer];
        UIBezierPath *path1 = [UIBezierPath bezierPath];
        shapeLayer.path = path1.CGPath;
        [path1 setLineWidth:0.5];
        [path1 moveToPoint:P1];
        [path1 addLineToPoint:P2];
        path1.lineCapStyle = kCGLineCapSquare;
        [self.graduationColor set];
        [path1 strokeWithBlendMode:kCGBlendModeNormal alpha:self.graduationAlpha];
    }
}

@end
